/*
 * Copyright 2025 author or author.
 * SPDX-License-Identifier: Apache-2.0
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.jcwang.commons.tools.util.encryption;

import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.util.Assert;

import java.security.MessageDigest;

/**
 * MD5加密工具类
 *
 * @author 王金城
 **/
public class MD5Utils {

    /**
     * MD5加盐加密
     *
     * @param hashIterations 加密迭代次数，此数值必须大于或等于 1
     * @param staticSalt     静态盐
     * @param salt           动态盐
     * @param text           加密文本
     * @return java.lang.String 加密后结果
     * @author 王金城
     */
    public static String saltMD5(final int hashIterations, final String staticSalt, final String salt, final String text) {
        if (hashIterations < 1) {
            throw new IllegalArgumentException("hashIterations 必须为大于或等于 1 的数字");
        }
        Assert.notNull(staticSalt, "静态盐值 staticSalt 不能为 null");
        Assert.notNull(salt, "动态盐值 salt 不能为 null");
        Assert.notNull(text, "需要加密的文本 text 不能为 null");
        MessageDigest md5Digest = DigestUtils.getMd5Digest();
        // 添加盐值
        md5Digest.update((staticSalt + salt).getBytes());
        // 这里已经执行了一次hash
        byte[] textBytes = md5Digest.digest(text.getBytes());
        // 如果需要执行多次 hash，通过此循环实现，由于之前已经hash过一次，所以 i 从 1 开始计算
        for (int i = 1; i < hashIterations; i++) {
            md5Digest.reset();
            textBytes = md5Digest.digest(textBytes);
        }
        return Hex.encodeHexString(textBytes);
    }

    /**
     * MD5加密字符串
     *
     * @param text 加密文本
     * @return java.lang.String 加密后结果
     * @author 王金城
     */
    public static String encode(final String text) {
        return DigestUtils.md5Hex(text);
    }
}
